<template>
  <PageListContainer>
    <div class="base-block">
      <k-search :model="state.params" @search="methods.onSearch" @reset="methods.onReset">
        <el-form-item label="用户搜索" prop="keyword">
          <el-input v-model="state.params.keyword" placeholder="请输入手机号/用户昵称" clearable />
        </el-form-item>

        <el-form-item label="成交意向" prop="deal_intent">
          <el-select v-model="state.params.deal_intent" placeholder="不限">
            <el-option v-for="item in purposeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="跟踪状态" prop="clue_follow_type">
          <el-select v-model="state.params.clue_follow_type" placeholder="不限">
            <el-option v-for="item in trackStateOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="公司规模" prop="company_size">
          <el-select v-model="state.params.company_size" placeholder="不限">
            <el-option v-for="item in companySizeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="到期版本" prop="product_title">
          <el-input v-model="state.params.product_title" placeholder="请输入版本号" clearable />
        </el-form-item>

        <el-form-item label="到期时间">
          <el-date-picker
            v-model="state.params._userTimeArr"
            clearable
            value-format="YYYYMMDD"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :shortcuts="dateShortcut"
            @change="methods.onSearch"
          />
        </el-form-item>
        <el-form-item label="企业微信" prop="enterprise_wechat">
          <el-select v-model="state.params.enterprise_wechat" placeholder="不限">
            <el-option v-for="item in addTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <!-- TODO： 去除线索类型 -->
        <el-form-item label="线索类型" prop="sales_user_type">
          <el-select v-model="state.params.sales_user_type" placeholder="不限">
            <el-option v-for="item in clueTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="最后访问">
          <el-date-picker
            v-model="state.params._lastLoginTimeArr"
            clearable
            value-format="YYYYMMDD"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :shortcuts="dateShortcut"
            @change="methods.onSearch"
          />
        </el-form-item>
        <el-form-item label="跟踪时间">
          <el-date-picker
            v-model="state.params._salesTimeArr"
            clearable
            value-format="YYYYMMDD"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :shortcuts="dateShortcut"
            @change="methods.onSearch"
          />
        </el-form-item>
      </k-search>
    </div>

    <div class="base-block">
      <k-toolbar>
        <el-button
          type="primary"
          :loading="fetchLoading"
          @click="onGetClues"
        >获取线索 ({{ countInfo.total_count - countInfo.sales_clue_count }} / {{ countInfo.total_count }})</el-button>
        <el-button :icon="Download" @click="onClickExportData">导出数据</el-button>
      </k-toolbar>
      <k-table v-bind="tableState" style="width: 100%" :default-sort="state.defaultSort" v-on="tableEvent">
        <template #mobile="{ row }">
          <el-link class="copy-btn" @click="onClickUserManger(row)">
            <el-icon class="copy-icon"><CopyDocument /></el-icon>
            {{ row.mobile }}
          </el-link>
        </template>
        <template #sales_end_time="{ row }">
          <DateCountDown :value="row.sales_end_time" />
        </template>
        <template #clue_follow_type="{ row }">
          <BaseStatus :value-map="statusColorMap" :value="row.clue_follow_type" />
        </template>
        <template #actions="{ row }">
          <el-link type="primary" @click="handleOpenDrawer(row)">操作</el-link>
          <el-link type="primary" @click="handleGiftVIP(row)">送会员</el-link>
        </template>
      </k-table>
    </div>
    <EditDrawer ref="drawerRef" @after-submit="handleAfterSubmit" />
  </PageListContainer>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { Download } from '@element-plus/icons-vue';
import { useTableList, clueTypeOptions, purposeOptions, trackStateOptions, addTypeOptions, companySizeOptions, statusColorMap } from './hooks/use-table';
import { getClueCount, addClue, giftVip } from '@/api/crm-kgj/sales';
import { baseConfirm } from '@crud/index';
import { exportMySalesClue } from '@/api/crm-kgj/download';
import { ElMessage } from 'element-plus';

import EditDrawer from './components/edit-drawer.vue';
import DateCountDown from '@/components/base-date-countdown/index.vue';
import BaseStatus from '@/components/base-status/index.vue';
import { toolGetDateRangeShorcuts as dateShortcut, toolCopyText } from '@/utils';
import { AuthCode, hasPermission } from '@/modules/auth';
defineOptions({
  name: 'KgjSalesMyClue'
});
const { state, tableState, tableEvent, ...methods } = useTableList({});
const router = useRouter();
const fetchLoading = ref(false);
const drawerRef = ref();

const countInfo = ref({
  sales_clue_count: 0,
  total_count: 0,
  give_level_count: 0
});
// 复制
const onClickCopy = (content: string) => {
  toolCopyText(content);
  ElMessage.success('复制成功');
};
// 点击手机号跳转
const onClickUserManger = (row: any) => {
  const { mobile } = row;
  onClickCopy(mobile);
  const link = router.resolve({ name: 'KgjUserManageIndex', query: { user_id: mobile } });
  window.open(link.href, '_blank');
};

const handleOpenDrawer = (row) => {
  if (hasPermission(AuthCode.KGJ_SALES_GET_MY_CLUE_LIST)) {
    drawerRef.value?.show(1, row);
  }
};
/** 导出数据 */
const onClickExportData = async () => {
  if (hasPermission(AuthCode.KGJ_SALES_GET_MY_CLUE_LIST)) {
    const res = await exportMySalesClue(methods.getParams(state.params).data);
    if (res.err) return;
  }
};
/** 获取线索 */
const onGetClues = async () => {
  if (hasPermission(AuthCode.KGJ_SALES_GET_MY_CLUE_LIST)) {
    fetchLoading.value = true;
    const res = await addClue();
    fetchLoading.value = false;
    if (res.err) return;
    handleGetClueCount();
    handleAfterSubmit();
  }
};
/** 请求获取线索的统计值 */
const handleGetClueCount = async () => {
  const res = await getClueCount();
  if (res.err) return;
  const { sales_clue_count, total_count, give_level_count } = res.data;
  countInfo.value = {
    sales_clue_count,
    total_count,
    give_level_count
  };
};
/** 打开送会员的弹窗 */
const handleGiftVIP = async (row = {}) => {
  if (hasPermission(AuthCode.KGJ_SALES_GET_MY_CLUE_LIST)) {
    const { sales_user_id } = row;
    await baseConfirm({ title: '赠送三天轻享会员', message: `确认要赠送三天轻享会员？本月剩余赠送${countInfo.value.give_level_count}次数` });
    const res = await giftVip({ sales_user_id });
    if (!res.err) {
      ElMessage.success('赠送成功');
      handleGetClueCount();
      handleAfterSubmit();
    }
  }
};
/** 保存成回调 */
const handleAfterSubmit = () => {
  methods.onSearch();
};
onMounted(() => {
  handleGetClueCount();
});
</script>
<style lang="scss" scoped>
.copy-btn {
  font-weight: normal;

  .copy-icon {
    margin-right: 2px;
  }

}
</style>
